<template>
  <view class="pay">
    <!-- 1 收货地址 -->
    <view class="address u-p-20">
        <!-- 添加判断if else，没有地址的时候就显示收货地址按钮 -->
      <view class="address-btn u-flex u-row-center"  v-if="!addressInfo">
        <u-button
          shape="circle"
          type="error"
          plain
          size="medium"
          :custom-style="{ backgroundColor: '#fff!important' }"
          @click="handleChooseAddress"
          >获取收货地址</u-button
        >
      </view>
      <view class="address-detail" v-else>
        <view class="address-detail">{{detail}}</view>
        <view class="address-user">{{addressInfo.userName}} {{addressInfo.telNumber}}</view>
      </view>
    </view>
    <u-line color="#eee"></u-line>
    <!-- 2 已选商品 -->
    <view class="goods-list u-p-15">
      <view class="goods-list-title">已选商品</view>
      <view class="goods-list-content">
        <view class="cart-item" v-for="item in checkedCartList" :key="item.goods_id">
          <!-- 2 图片 -->
          <view class="goods-img">
            <u-image width="191rpx" height="191rpx" :src="item.goods_small_logo"></u-image>
          </view>
          <!-- 3 信息 -->
          <view class="goods-info">
            <!-- 名称 -->
            <view class="goods-name u-line-2">{{item.goods_name}}</view>
            <!-- 价格和数量 -->
            <view class="goods-price-num">
              <view class="goods-price">￥{{item.goods_price}}</view>
              <view class="goods-num-tool">
                <view class="goods-vnum">X{{item.num}}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 2 统计 -->
    <view class="statistics">
      <view class="all-price"> 合计: <text>￥{{totalPrice}}</text> </view>
      <view class="all-count">
        <u-button type="error" shape="circle" @click="handlePay">去支付({{totalCount}})</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import {mapGetters} from "vuex"
export default {
    data(){
        return{
            // 收货地址信息
            addressInfo:null
        }
    },
    // computed缓存计算结果，数据有变化页面会随之变化
    computed:{
        ...mapGetters('cart',['checkedCartList','totalCount','totalPrice']),
        // 用户的详细收货地址
        detail(){
      // cityName: "广州市"
      // countyName: "海珠区"
      // detailInfo: "新港中路397号"
      // errMsg: "chooseAddress:ok"
      // nationalCode: "510000"
      // postalCode: "510000"
      // provinceName: "广东省"
      // telNumber: "020-81167888"
      // userName: "张三"
      if(!this.addressInfo) return''
      const{provinceName,cityName,countyName,detailInfo}=this.addressInfo
      return provinceName+cityName+countyName+detailInfo
        }
    },
    methods:{
        // 获取收货地址
        async handleChooseAddress(){
            // chooseAddress是微信小程序获取用户填写的地址的api
            const[err,addressInfo]=await uni.chooseAddress()
            if(err){
                console.log(err);
            }else{
                this.addressInfo=addressInfo
                console.log(this.addressInfo);
            }
        },
        // 点击去支付
       async handlePay(){
            // 1、判断用户有没有选择收货地址
            if(!this.addressInfo){
                uni.showToast({
                    title:"还没有选择收货地址哦",
                    icon:'none'
                })
                return
            }
            // 2、调用小程序的api获取当前用户系信息
            const [err1,res1]=await uni.getUserProfile({
                desc:"给用户更好的体验",
            })
            // 获取接口的要用户信息
            const{encryptedData, rawData, iv, signature}=res1
            // 3、执行微信的登录 login 获取临时登录凭据
            const [err2,res2]=await uni.login()
            const {code}=res2
            // 4、向后端取token,发请求,五个必传值
            const res3=await this.$u.http.post('users/wxlogin',{
            encryptedData,
            rawData,
            iv,
            signature,
            code,
            })
            const {token}=res3
            // 5、创建订单
      // 5.1 构造 请求体的参数
      // order_price	是	string	订单总价格
      // consignee_addr	是	string	收货地址
      // goods	是	Array	订单数组
      const orderParams={
          order_price:this.totalPrice,
          consignee_addr:this.detail,
          goods:this.checkedCartList.map((goods)=>({
              goods_id:goods.goods_id,
              goods_number:goods.num,
              goods_price:goods.goods_price
          })),
      };


    //   5.2开始发请求，拿到一个订单编号，传一个请求头（ Authorization）和请求体（orderParams）
    const res4=await this.$u.http.post('/my/orders/create',orderParams,{
        Authorization: token,
    })
    const{order_number}=res4

    // 5.3、发起支付流程 获取支付参数，参一个请求头和请求体订单编号
    const res5=await this.$u.http.post("/my/orders/req_unifiedorder",
    {order_number},{Authorization:token})
    const{pay}=res5
    // 开始调起微信支付
    uni.requestPayment(pay)
        }
    }
};
</script>

<style lang="scss">
.pay {
  padding-bottom: 111rpx;
}
.cart-item {
  display: flex;
  padding: 10rpx;
  border-bottom: 1rpx solid #ccc;

  .goods-img {
    flex: 2;

    display: flex;
    align-items: center;
    justify-content: center;
  }

  .goods-info {
    color: #666;
    flex: 3;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .goods-name {
    }

    .goods-price-num {
      display: flex;
      justify-content: space-between;
      .goods-price {
        color: $theme-color;
      }

      .goods-num-tool {
        width: 140rpx;
        height: 40rpx;

        display: flex;
        justify-content: flex-end;

        .goods-vnum {
        }
      }
    }
  }
}
.statistics {
  position: fixed;
  background-color: #fff;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  border-top: 1rpx solid #ccc;
  display: flex;
  align-items: center;
  padding: 15rpx;
  .all-price {
    flex: 1;
    color: #666;
    text {
    }
  }

  .all-count {
  }
}
</style>